package cn.fulong.sso.client.servlet;


import cn.fulong.sso.client.manager.SessionManager;
import cn.fulong.sso.client.utils.SessionManagerUtils;
import cn.fulong.sso.client.utils.StringSelfUtil;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;


/**
 * @desc: 服务端回调客户端退出客户端
 * @author: 云树
 * @createDate: 2019/1/16 20:55
 * @version: 1.0
 */
@Slf4j
public class SsoClientLogoutServlet extends HttpServlet {

    private SessionManager sessionManager;

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        ServletContext servletContext = this.getServletContext();
        //获取SSo服务端全局配置
        this.sessionManager = SessionManagerUtils.getRegisterSessionMangerBean(servletContext);
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String token = req.getParameter("token");
        log.debug("退出token={}", token);
        if (StringSelfUtil.isBlank(token)) {
            log.warn("退出token参数为空");
            redirectError(resp, "params-empty");
            return;
        }
        boolean flag = sessionManager.removeSessionManagerByToken(token);
        if (flag) {
            log.debug("客户端退出成功token={}", token);
            redirectError(resp, "1");
            return;
        }
        log.error("客户端退出失败token={}", token);
        redirectError(resp, "0");
        return;
    }

    private void redirectError(HttpServletResponse response, String code) throws IOException {
        PrintWriter out = response.getWriter();
        out.print(code);
    }
}
